let WebIM = require("/WebIM")["default"];

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}



// 格式化时间戳
function getTime(timestamp) {
  var time = arguments[0] || 0;
  var t, y, m, d, h, i, s;
  t = time ? new Date(time * 1000) : new Date();
  y = t.getFullYear(); // 年
  m = t.getMonth() + 1; // 月
  d = t.getDate(); // 日

  h = t.getHours(); // 时
  i = t.getMinutes(); // 分
  s = t.getSeconds(); // 秒

  return [y, m, d].map(formatNumber).join('-') + ' ' + [h, i, s].map(formatNumber).join(':');

}

function getDateDiff(dateTimeStamp) {
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var year = day * 365;
  var now = new Date().getTime();
  //   console.log(now);
  var diffValue = now - dateTimeStamp;
  if (diffValue < 0) {
    //非法操作
    return '数据出错';
  }
  var yearC = diffValue / year;
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;
  var result = '';
  if (yearC >= 1) {
    result = parseInt(yearC) + '年以前';
  } else if (monthC >= 1) {
    result = parseInt(monthC) + '个月前';
  } else if (weekC >= 1) {
    result = parseInt(weekC) + '星期前';
  } else if (dayC >= 1) {
    result = parseInt(dayC) + '天前';
  } else if (hourC >= 1) {
    result = parseInt(hourC) + '小时前';
  } else if (minC >= 5) {
    result = parseInt(minC) + '分钟前';
  } else {
    result = '刚刚发表';
  }
  return result;
}

function getFormatDate(str) {

  // 拆分日期为年 月 日
  var YEAR = str.substring(0, 4),
    MONTH = str.substring(4, 6),
    DATE = str.slice(-2);

  // 拼接为 2016/10/02 可用于请求日期格式
  var dateDay = YEAR + "/" + MONTH + "/" + DATE;

  // 获取星期几
  var week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    day = new Date(dateDay).getDay();

  return {
    "dateDay": MONTH + "月" + DATE + "日 " + week[day]
  }

}

function downloadFileAndSave(url) {
  wx.downloadFile({
    url: url,
    success: function (res) {
      saveImageToPhotosAlbum(res.tempFilePath);
    }
  })
}

function getImageInfoAndSave(src) {
  wx.getImageInfo({
    src: src,
    success: function (res) {
      saveImageToPhotosAlbum(res.path);
    }
  })
}

function saveImageToPhotosAlbum(filePath) {
  wx.saveImageToPhotosAlbum({
    filePath: filePath,
    success(res) {
      console.log("saveImg:" + res);
      wx.showModal({
        title: "保存成功！"
      });
    }
  })
}


function GetJson(url, data, fn) {
  wx.request({
    url: url,
    data: data,
    method: "GET",
    header: {
      "Content-Type": "application/json"
    },
    success: function (res) {
      fn(res);
      // 存储数据
      // wx.setStorageSync(url, res);
    },
    fail: function (err) {
      // 取出数据
      // var res = wx.getStorageSync(url)
      // if (res) {
      //   fn(res);
      // }
      console.log(err)
    }
  });
}

function PostRequest(url, data, fn) {
  wx.request({
    url: url,
    data: data,
    method: "POST",
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      fn(res);
    },
    fail: function (err) {
      console.log(err)
    }
  })
}

function formatMyTime(time) {
  if (typeof time !== 'number' || time < 0) {
    return time
  }

  var hour = parseInt(time / 3600)
  time = time % 3600
  var minute = parseInt(time / 60)
  time = time % 60
  var second = time

  return ([minute, second]).map(function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }).join(':')
}

/**
 * 正则截取字符串
 */
function getRegex(sourceStr, regexStr) {
  var dataArray = sourceStr.match(new RegExp(regexStr));
  if (dataArray && dataArray.length > 1) {
    console.log(dataArray[1]);
    return dataArray[1];
  } else {
    return '';
  }
}

function setTabBarData(userData) {
  var tabBar = [];
  var user = userData.userinfo;
  var taskUnRead = userData.taskUnRead;
  var msgUnread = userData.msgUnread;
  var xcTaskUndone = userData.xcTaskUndone;

  var easemobIM = wx.getStorageSync("easemobIM");

  if (user.is_reporter == 1) {

    wx.setStorage({
      key: "myUsername",
      data: user.mobile
    });

    if (easemobIM == 1) {

      if (!WebIM.conn.isOpening() && !WebIM.conn.isOpened()) {

        getApp().conn.open({
          apiUrl: WebIM.config.apiURL,
          user: user.mobile,
          pwd: "longsunhd_159456",
          grant_type: "password",
          appKey: WebIM.config.appkey
        });
      }

      tabBar = [{
          "pagePath": "/pages/task/index",
          "iconPath": "/image/task_gray.png",
          "selectedIconPath": "/image/task_blue.png",
          "text": "任务",
          "badge": taskUnRead
        },
        {
          "pagePath": "/pages/im/chat/chat",
          "iconPath": "/image/im_gray.png",
          "selectedIconPath": "/image/im_blue.png",
          "text": "会话"
        },
        {
          "pagePath": "/pages/library/index",
          "iconPath": "/image/library_gray.png",
          "selectedIconPath": "/image/library_blue.png",
          "text": "稿库"
        },
        {
          "pagePath": "/pages/me/index",
          "iconPath": "/image/me_gray.png",
          "selectedIconPath": "/image/me_blue.png",
          "text": "我的",
          "badge": msgUnread
        }
      ];

    } else {
      tabBar = [{
          "pagePath": "/pages/task/index",
          "iconPath": "/image/task_gray.png",
          "selectedIconPath": "/image/task_blue.png",
          "text": "任务",
          "badge": taskUnRead
        },
        {
          "pagePath": "/pages/library/index",
          "iconPath": "/image/library_gray.png",
          "selectedIconPath": "/image/library_blue.png",
          "text": "稿库"
        },
        {
          "pagePath": "/pages/me/index",
          "iconPath": "/image/me_gray.png",
          "selectedIconPath": "/image/me_blue.png",
          "text": "我的",
          "badge": msgUnread
        }
      ];
    }

    console.log("设置tabBar(任务)");

  } else {


    var user_role = wx.getStorageSync("user_role");
    if (user_role == "editor") {

      tabBar = [{
          "pagePath": "/pages/audit/index",
          "iconPath": "/image/audit_gray.png",
          "selectedIconPath": "/image/audit_blue.png",
          "text": "编审"
        },
        {
          "pagePath": "/pages/library/index",
          "iconPath": "/image/library_gray.png",
          "selectedIconPath": "/image/library_blue.png",
          "text": "稿库"
        },
        {
          "pagePath": "/pages/me/index",
          "iconPath": "/image/me_gray.png",
          "selectedIconPath": "/image/me_blue.png",
          "text": "我的",
          "badge": msgUnread + xcTaskUndone
        }
      ];
      console.log("设置tabBar(编审）");
    } else {
      tabBar = [{
          "pagePath": "/pages/task/index",
          "iconPath": "/image/task_gray.png",
          "selectedIconPath": "/image/task_blue.png",
          "text": "任务",
          "badge": taskUnRead
        },
        {
          "pagePath": "/pages/library/index",
          "iconPath": "/image/library_gray.png",
          "selectedIconPath": "/image/library_blue.png",
          "text": "稿库"
        },
        {
          "pagePath": "/pages/me/index",
          "iconPath": "/image/me_gray.png",
          "selectedIconPath": "/image/me_blue.png",
          "text": "我的",
          "badge": msgUnread
        }
      ];

      console.log("设置tabBar(任务)");
    }
  }

  wx.setStorageSync("tabBar", tabBar);

  return tabBar;
}

function getReporter(mobile) {
  var reporterList = wx.getStorageSync("reporterList");
  var reporterItem = null;
  if (reporterList) {
    for (var i = 0; i < reporterList.length; i++) {
      var tmobile = reporterList[i].mobile;
      if (tmobile == mobile) {
        reporterItem = reporterList[i];
      }
    }
  }
  return reporterItem;
}

/**
 *  data 需要传入的去除null值的对象或者值
 *  defaultStr 将null值转为该字符串, 不传默认为 空字符串 ''
 */
function removeNull(data, defaultStr = '') {
  // 普通数据类型
  if (typeof data != 'object' || data == null) {
    if ((data == null || data == 'null')) {
      return defaultStr;
    } else {
      return data;
    }
  }
  // 引用数据类型
  for (const v in data) {
    if (data[v] == null || data[v] == 'null') {
      data[v] = defaultStr;
    }
    if (typeof data[v] == 'object') {
      removeNull(data[v])
    }
  }
}

module.exports = {
  APPID: 'wxcb88295a9cb8024f',
  tmplID: 'yNXZNJVEOstasbnpjmLswyXua27n1-H0wOECDUB-wc4',
  Version: 'v1.0.10',
  themeColor: '#f83228',
  formatTime: formatTime,
  formatMyTime: formatMyTime,
  getTime: getTime,
  getDateDiff: getDateDiff,
  GetJson: GetJson,
  PostRequest: PostRequest,
  getFormatDate: getFormatDate,
  downloadFileAndSave: downloadFileAndSave,
  getImageInfoAndSave: getImageInfoAndSave,
  getRegex: getRegex,
  setTabBarData: setTabBarData,
  getReporter: getReporter,
  removeNull: removeNull
}